using Eno.Application.Dto;
using Eno.Infrastructure.Services;

namespace Eno.Application.Services;

public class AuthServices
{
    private readonly UserService _userService;
    private readonly PasswordService _passwordService;
    private readonly IJwtService _jwtService;

    public AuthServices(UserService userService, PasswordService passwordService, IJwtService jwtService)
    {
        _userService = userService;
        _passwordService = passwordService;
        _jwtService = jwtService;
    }

    public async Task<int> RegisterAsync(UserDto dto)
    {
        var user = await _userService.GetUserAccount(dto.Account);
        if (user != null) return 0;
        return await _userService.AddUserAsync(dto);


    }
    // 用户登录功能
    public async Task<bool> EnterAsync(UserDto dto)
    {
        var user = await _userService.GetUserAccount(dto.Account);
        if (user == null)
        {
            return false;
        }
        // 先用用户的Salt对输入密码进行加密
        var inputPwdHash = _passwordService.HashPassword(dto.Password, user.Salt);
        if (user.Password != inputPwdHash)
        {
            return false;
        }
        return true;
    }
    public async Task<string> GenerateTokenAsync(string username)
    {
        // 获取用户信息
        var user = await _userService.GetUserAccount(username);
        if (user == null)
            throw new Exception("用户不存在,无法生成Token");

        // 获取用户角色（假设有 GetUserRolesAsync 方法，返回 List<string>）
        var roles = await _userService.GetUserRolesAsync(user.ID);

        // 调用 JWT 服务生成 Token
        return _jwtService.GenerateToken(user.ID.ToString(), user.Account, roles);
    }
}